package myQueue;

public class MyCircleLinkedQueue<T> {
    LinkNode<T> rear;                //尾结点指针

    public MyCircleLinkedQueue()            //构造方法
    {
        rear = null;
    }

    //队列的基本运算算法
    public boolean empty()            //判断队是否为空
    {
        return rear == null;
    }

    public void push(T e)            //元素e进队
    {
        LinkNode<T> s = new LinkNode(e);    //创建新结点s
        if (rear == null)            //原链队为空
        {
            s.next = s;            //构成循环单链表
            rear = s;
        } else {
            s.next = rear.next;        //将s结点插入到rear结点之后
            rear.next = s;
            rear = s;                //让rear指向s结点
        }
    }

    public T pop()                    //出队操作
    {
        T e;
        if (empty())                //原链队不空
            throw new IllegalArgumentException("队空");
        if (rear.next == rear)            //原链队只有一个结点
        {
            e = (T) rear.data;                //取该结点值
            rear = null;                //置为空队
        } else                        //原链队有多个结点
        {
            e = (T) rear.next.data;            //取队头结点值
            rear.next = rear.next.next;        //删除队头结点
        }
        return e;
    }

    public T peek()            //取队顶元素操作
    {
        T e;
        if (empty())            //原链队不空
            throw new IllegalArgumentException("队空");
        if (rear.next == rear)        //原链队只有一个结点
            e = (T) rear.data;        //取该结点值
        else                //原链队有多个结点
            e = (T) rear.next.data;        //取队头结点值
        return e;
    }

}
